<?php

namespace teach\service;

use Yii;

class Material
{
    public function menuList($map, $page, $pre_page = 10)
    {
        $count = $this->menuCount($map);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil($count / $pre_page);

            $offset = ($page - 1) * $pre_page;
            $sql = "SELECT id, title,parent_id,rank,cover_url FROM mall_material_menu WHERE {$map} ORDER BY sort DESC LIMIT {$offset}, {$pre_page}";
            $res = Yii::$app->db->createCommand($sql)->queryAll();

            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }
        return $data;
    }

    /**
     * 统计菜单数量
     * @param $map
     * @return int
     */
    public function menuCount($map)
    {
        $sql = "SELECT COUNT(*) FROM mall_material_menu WHERE {$map}";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    public function materialList($map, $page, $pre_page = 10)
    {
        $count = $this->materialCount($map);
        $data = ['total' => 0, 'total_page' => 0, 'page' => 1, 'pre_page' => $pre_page, 'lists' => []];

        if ($count) {
            $total_page = ceil($count / $pre_page);

            $offset = ($page - 1) * $pre_page;
            $sql = "SELECT m.id, m.mid, m.title,m.style, m.words, m.publisher_id,m.img_url, m.video_url, m.down_count, m.sort, m.status, p.name, p.avatar_url FROM mall_material AS m LEFT JOIN  mall_publisher AS p ON m.publisher_id = p.id WHERE {$map} ORDER BY m.sort DESC, m.create_time DESC LIMIT {$offset}, {$pre_page}";
            $res = Yii::$app->db->createCommand($sql)->queryAll();

            $data = ['total' => $count, 'total_page' => $total_page, 'page' => $page, 'pre_page' => $pre_page, 'lists' => $res];
        }
        return $data;
    }

    /**
     * 计算数量
     * @param $map
     * @return false|null|string
     */
    public function materialCount($map)
    {
        $sql = "SELECT COUNT(*) FROM mall_material AS m WHERE {$map}";
        return Yii::$app->db->createCommand($sql)->queryScalar();
    }

    /**
     * 获取详情
     * @param $map
     * @return array|false
     */
    public function materialDetail($map)
    {
        $sql = "SELECT m.mid, m.style, m.words, m.img_url, m.video_url, m.down_count, m.status, p.name, p.avatar_url FROM mall_material AS m  LEFT JOIN mall_publisher AS p ON m.publisher_id = p.id WHERE {$map}";
        return Yii::$app->db->createCommand($sql)->queryOne();
    }
}